import React, { useState, useRef, useEffect } from 'react';
import { useDrag, useDrop, DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

const DraggableItem = ({ droppedItems, itemKey, changeDropHover }) => {
    const SiderItem = ({ name, id, index }) => {
        const SiderItemRef = useRef(null);
        const [, drag] = useDrag(() => ({
            type: `main-item-${itemKey}`,
            item: { name, id },
            isDragging: (monitor) => {
                return index === monitor.getItem().index;
            },
            collect: (monitor) => ({
                isDragging: monitor.isDragging(),
            }),
        }));
        const [, drop] = useDrop(() => ({
            accept: `main-item-${itemKey}`,
            hover: (item, monitor) => {
                if (!SiderItemRef.current) return;
                let dragIndex = droppedItems?.findIndex((f) => f.id === item.id)
                let hoverIndex = index;
                if (dragIndex === hoverIndex) return;
                changeDropHover(dragIndex, hoverIndex,itemKey);
            },
            drop: (item, monitor) => {

            },
        }));

        drag(drop(SiderItemRef))

        return <span ref={SiderItemRef} className={`main-item-col-row`} key={id} style={{ padding: '5px', border: '1px solid gray', margin: '5px', borderRadius: '5px', transition: 'all 0.3s ease' }}>{name}</span>
    }
    return <DndProvider backend={HTML5Backend}>
        <div className={'main-item-' + itemKey}>
            {!!droppedItems?.length && droppedItems.map((droppedItem, index) => (
                <SiderItem key={droppedItem.id} name={droppedItem.name} id={droppedItem.id} index={index} />
            ))}
        </div>
    </DndProvider>
}


export default DraggableItem